package ink.metoo.gude.config.jpa.hibernate.strategy

import org.hibernate.boot.Metadata
import org.hibernate.boot.model.relational.ColumnOrderingStrategyStandard
import org.hibernate.mapping.Column
import org.hibernate.mapping.Table

class SimpleColumnOrderingStrategy : ColumnOrderingStrategyStandard() {

    override fun orderTableColumns(
        table: Table,
        metadata: Metadata
    ): List<Column> = table.columns.sortedWith(SimpleColumnComparator(metadata))

    private class SimpleColumnComparator(metadata: Metadata) : ColumnComparator(metadata) {

        override fun compare(o1: Column, o2: Column): Int {
            // identity column first
            if (o1.isIdentity && !o2.isIdentity) return 0
            if (o1.isIdentity) return -1
            if (o2.isIdentity) return 1

            // end column last
            val o1Contains = END_COLUMN.contains(o1.name)
            val o2Contains = END_COLUMN.contains(o2.name)

            if (o1Contains && o2Contains) return 0
            if (o1Contains) return 1
            if (o2Contains) return -1

            return super.compare(o1, o2)
        }

        companion object {
            val END_COLUMN = arrayOf("last_modified_date", "create_date")
        }
    }


}